package cn.sdut.training.web.action;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import cn.sdut.training.domain.Academy;
import cn.sdut.training.domain.Majore;
import cn.sdut.training.domain.User;
import cn.sdut.training.service.TrainingService;
import cn.sdut.training.service.UserService;

public class RegAction extends ActionSupport {

	private static final long serialVersionUID = 3985717096235277898L;

	private User user;

	// 注册页面相关数据（学院/专业）
	private List<Academy> academyList;
	private Long majoreId;
	private Long academyId;
	
	@Resource
	private TrainingService trainingService;
	
	@Resource
	private UserService userService;

	// ---------------------------------------------

	/*
	 * 转到注册界面
	 */
	public String toRegisterPage() {
		academyList = trainingService.findAllAcademy();
		return "toRegisterPage";
	}

	/**
	 * 生成学院的专业信息返回给客户端
	 * 
	 * @return
	 */
	public String getMajoresByAcademyId() {
		System.out.println(academyId);
		Academy academy = trainingService.getAcademyById(academyId);
		Set<Majore> majores = academy.getMajores();
		String result = "<select name='majoreId'>";
		for (Majore majore : majores) {
			result += "<option value='" + majore.getId() + "'>" + majore.getName() + "</option>";
		}
		result += "</select>";
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 处理注册请求
	 */
	public String register() {
		Academy academy = trainingService.getAcademyById(academyId);
		Majore majore = trainingService.getMajoreById(majoreId);
		user.setMajore(majore);
		user.setAcademy(academy);
		userService.saveUser(user);
		return "registerSuccess";
	}

	// -----------------------------------------------
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<Academy> getAcademyList() {
		return academyList;
	}

	public void setAcademyList(List<Academy> academyList) {
		this.academyList = academyList;
	}

	public Long getMajoreId() {
		return majoreId;
	}

	public void setMajoreId(Long majoreId) {
		this.majoreId = majoreId;
	}

	public Long getAcademyId() {
		return academyId;
	}

	public void setAcademyId(Long academyId) {
		this.academyId = academyId;
	}

}
